import React, { useState } from 'react';
import Upload from 'rc-upload';
import { useWait, Btn, WaitDlg } from '../../nui';
import { loc } from '../../local';

const { convertCSVToArray } = require('convert-csv-to-array');
const csv = require('csvtojson');

/* hcmd: hcmd(data, fname)
 * file: csv file
*/
const read_file = (file, hcmd, tojson=true, ft="csv") => {
    let reader = new FileReader();
    reader.readAsText(file);

    reader.onload = event => {
        if (ft === "csv") {
            if (tojson) {
                csv().fromString(event.target.result)
                    .then(data => hcmd(data, file.name));
            }
            else {
                const data = convertCSVToArray(event.target.result, {
                    type: 'array',
                });

                hcmd(data, file.name);
            }
        }
        else {
            hcmd(event.target.result, file.name);
        }
    }
};

/* hcmd: hcmd(data, fname)
*/
const Upcsv = ({ name="upload", title, mfile=false, hcmd, tojson=true, ft="csv", disabled=false }) => {
    const props = {
        multiple: mfile,
        beforeUpload(file) {
            read_file(file, hcmd, tojson, ft);
            return false;
        }
    };

    return (
        <Upload {...props}>
            <Btn name={name} disabled={disabled}>
                {title}
            </Btn>
        </Upload>
    );
};

/* hcmd: hcmd(data, umd)
*/
const BtImport = ({ label, umd, hcmd, className, tojson=true, ft="csv", disabled=false }) => (
    <div className={className}>
        <Upcsv tojson={tojson} title={label} hcmd={v => hcmd(v, umd)} ft={ft} disabled={disabled}/>
    </div>
);

const UpFile =({ hcmd, title, action, name="upload", className, ckxlsx, ckname, disabled=false }) => {
    const [wait, wrong, startWait, endWait, setWrong] = useWait();
    const [filename, setFilename] = useState();

    const props = {
        action: action,
        multiple: false,
        beforeUpload(file) {
            const fn = file.name;

            if (ckxlsx) {
                if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" !== file.type && ".xlsx" !== fn.slice(-5)) {
                    alert(loc("upfile0"));
                    return false;
                }
            }

            if (ckname) {
                if (ckname !== file.name) {
                    alert(`${loc("zqf")} ${ckname}`);
                    return false;
                }
            }

            setFilename(fn);
            startWait();
            return true;
        },
        onSuccess(file) {
            if (hcmd) {
                hcmd(endWait, filename);
            }
        },
        onError(err) {
            console.log(err);
            const v = JSON.stringify(err);
            setWrong(`${loc("upfail")}: ${v}`);
        }
    };

    return (
        <div className={className}>
            <Upload {...props}>
                <Btn name={name} disabled={disabled}>
                    {title}
                </Btn>
            </Upload>
            <WaitDlg wrong={wrong} wait={wait} hwait={endWait}/>
        </div>
    );
};

export {BtImport, UpFile};
